package com.ewanghuiju.app.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;

import com.ewanghuiju.app.R;
import com.makeramen.roundedimageview.RoundedImageView;

import androidx.appcompat.widget.AppCompatImageView;

/**
 * @author sj  qq:751943509
 * @class 宽高比列的 imageview
 * @time 2020/2/20
 */
public class FixImageview extends RoundedImageView {
    private static final int FIXED_WIDTH = 0;
    private static final int FIXED_HEIGHT = 1;
    private int mAspectRatioWidth = 0;
    private int mAspectRatioHeight = 0;
    private int mFixedAspect;

    public FixImageview(Context context) {
        super(context);
    }

    public FixImageview(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public FixImageview(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.FixedAspectRatioView);
        mAspectRatioWidth = a.getInt(R.styleable.FixedAspectRatioView_aspectRatioWidth, 0);
        mAspectRatioHeight = a.getInt(R.styleable.FixedAspectRatioView_aspectRatioHeight, 0);
        mFixedAspect = a.getInt(R.styleable.FixedAspectRatioView_fixedAspect, FIXED_WIDTH);
        a.recycle();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (mAspectRatioHeight == 0 || mAspectRatioWidth == 0) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        } else {
            int originalWidth = MeasureSpec.getSize(widthMeasureSpec);
            int originalHeight = MeasureSpec.getSize(heightMeasureSpec);
            int calculatedHeight = originalWidth * mAspectRatioHeight / mAspectRatioWidth;
            int expectedWidth, expectedHeight;
            if (mFixedAspect == FIXED_WIDTH) {
                expectedWidth = originalWidth;
                expectedHeight = calculatedHeight;
            } else {
                expectedWidth = originalHeight * mAspectRatioWidth / mAspectRatioHeight;
                expectedHeight = originalHeight;
            }
            super.onMeasure(MeasureSpec.makeMeasureSpec(expectedWidth, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(expectedHeight, MeasureSpec.EXACTLY));
        }
    }
}